package com.eva.admin.biz.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eva.admin.dao.system.dto.QuerySystemJobLogDTO;
import com.eva.dao.system.model.SystemJobLog;
import com.eva.framework.common.model.PageData;
import com.eva.framework.common.model.PageWrap;
import com.eva.framework.common.utils.AssertUtil;
import com.eva.framework.common.utils.Utils;
import com.eva.service.system.SystemJobLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SystemJobLogBiz {

    @Resource
    private SystemJobLogService systemJobLogService;

    /**
     * 根据主键删除
     *
     * @param id 主键
     */
    @Transactional
    public void deleteById(Integer id) {
        AssertUtil.notEmpty(id, "主键不能为空");
        systemJobLogService.deleteById(id, Boolean.TRUE);
    }

    /**
     * 根据主键批量删除
     *
     * @param ids 主键集合
     */
    @Transactional
    public void deleteByIdInBatch(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        for (Integer id : ids) {
            this.deleteById(id);
        }
    }

    /**
     * 分页查询
     *
     * @param pageWrap 分页参数
     * @return 分页数据
     */
    public PageData<SystemJobLog> findPage(PageWrap<QuerySystemJobLogDTO> pageWrap) {
        QueryWrapper<SystemJobLog> queryWrapper = new QueryWrapper<>();
        QuerySystemJobLogDTO queryDto = pageWrap.getModel();
        Utils.MP.blankToNull(queryDto);
        queryWrapper.lambda()
                .eq(queryDto.getJobId() != null, SystemJobLog::getJobId, queryDto.getJobId())
                .ge(queryDto.getBusinessTime() != null, SystemJobLog::getBusinessTime, Utils.Date.getStart(queryDto.getBusinessTime()))
                .le(queryDto.getBusinessTime() != null, SystemJobLog::getBusinessTime, Utils.Date.getEnd(queryDto.getBusinessTime()))
                .eq(queryDto.getServerIp() != null, SystemJobLog::getServerIp, queryDto.getServerIp())
                .eq(queryDto.getTriggerType() != null, SystemJobLog::getTriggerType, queryDto.getTriggerType())
                .eq(queryDto.getStatus() != null, SystemJobLog::getStatus, queryDto.getStatus());
        for(PageWrap.SortData sortData: pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
                queryWrapper.orderByDesc(sortData.getProperty());
            } else {
                queryWrapper.orderByAsc(sortData.getProperty());
            }
        }
        return systemJobLogService.findPage(pageWrap.getPage(), pageWrap.getCapacity(), queryWrapper);
    }
}
